<template>
	<div class="category">
		<curr-app :left="245"></curr-app>
		<list-title :data="header"></list-title>
		<el-form :model="categoryForm" :rules="rules" ref="categoryForm" label-width="200px">
			<el-form-item label="栏目名称" prop="data.name" style="width: 600px;">
				<el-input v-model="categoryForm.data.name" placeholder="栏目名称"></el-input>
			</el-form-item>
			<el-form-item label="栏目别名" prop="data.alias" style="width: 600px;">
				<el-input v-model="categoryForm.data.alias" placeholder="栏目别名"></el-input>
			</el-form-item>
			<el-form-item label="Icon图标" prop="data.icon" style="width: 275px;">
				<!-- <upload :domain="this.$domain.cms" :limit="1" :fileList="categoryForm.data.icon" :maxSize="20" :appid="$route.query.appid" :field="'icon'" @insertPic="insertPic" @delPic="delPic"></upload> -->
				<upload-oss 
				:stsdomain="this.$domain.ac" 
				:ossdomain="this.$ossdomain" 
				:appid="$route.query.appid" 
				:limit="1" 
				:fileList="categoryForm.data.icon" 
				:maxSize="20" 
				@insertFile="insertIcon"
				@delFile="delIcon">
				</upload-oss>
			</el-form-item>
			<el-form-item label="上级栏目" prop="data.parentid">
				<el-select v-model="categoryForm.data.parentid" placeholder="请选择上级栏目">
					<el-option label="顶级栏目" value="0"></el-option>
					<el-option v-for="(item, index) in categoryList" :key="index" :label="item.name" :value="item.catid"></el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="预览图" prop="data.preview" style="width: 420px;">
				<!-- <upload :domain="this.$domain.cms" :limit="3" :fileList="categoryForm.data.preview" :maxSize="20" :appid="$route.query.appid" :field="'preview'" @insertPic="insertPic" @delPic="delPic"></upload> -->
				<upload-oss 
				:stsdomain="this.$domain.ac" 
				:ossdomain="this.$ossdomain" 
				:appid="$route.query.appid" 
				:limit="3" 
				:fileList="categoryForm.data.preview" 
				:maxSize="20" 
				@insertFile="insertPreview"
				@delFile="delPreview">
				</upload-oss>
			</el-form-item>
			<el-form-item label="标签" style="width: 680px;">
				<el-input type="text" placeholder="请输入标签" v-model='newTags' maxlength="16" show-word-limit style="width: 275px;"></el-input>
				<el-button @click="createTag()">添加</el-button>
				<el-button type="primary" @click="getHotTags()" :disabled='tagsLibLock'>
					常用标签选择  <span class="el-icon-loading" v-if='tagsLibLock'></span>
				</el-button>
				<p class="help">多个标签请用英文逗号（,）分开</p>
				<ul class="tag" v-if='categoryForm.tags.length > 0'>
					<li v-for="(item, index) in categoryForm.tags" :key="index">
						<span>{{ item.tag_name }}</span>
						<i @click="removeTag(index)">×</i>
					</li>
				</ul>
				<ul class="tag-lib" v-if='tagsLib.length > 0'>
					<li v-for="(item, index) in tagsLib" :key="index">
						<span @click="addTag(item)">{{ item.tag_name }}</span>
					</li>
				</ul>
			</el-form-item>
			<el-form-item label="SEO标题" prop="data.seo_title" style="width: 600px;">
				<el-input v-model="categoryForm.data.seo_title" placeholder="SEO标题"></el-input>
			</el-form-item>
			<el-form-item label="SEO关键词" prop="data.seo_keyword" style="width: 600px;">
				<el-input v-model="categoryForm.data.seo_keyword" placeholder="SEO关键词"></el-input>
			</el-form-item>
			<el-form-item label="描述" prop="data.seo_describe" style="width: 600px;">
				<el-input type="textarea" :rows="5" placeholder="请输入描述" v-model="categoryForm.data.seo_describe"></el-input>
			</el-form-item>
			<el-form-item label="是否外链" prop="data.outside">
				<el-switch v-model="categoryForm.data.outside"></el-switch>
			</el-form-item>
			<el-form-item label="打开方式" v-if="categoryForm.data.outside" prop="data.url_target" style="width: 600px;">
				<el-select v-model="categoryForm.data.url_target" placeholder="请选择打开方式">
					<el-option label="self" :value="'1'"></el-option>
					<el-option label="blank" :value="'2'"></el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="外链地址" v-if="categoryForm.data.outside" prop="data.outside_url" style="width: 600px;">
				<el-input v-model="categoryForm.data.outside_url" placeholder="外链地址"></el-input>
			</el-form-item>
			<el-form-item label="类型" v-if="(!categoryForm.data.outside)" prop="data.flag">
				<template>
					<el-radio v-model="categoryForm.data.flag" label="1">单页</el-radio>
					<el-radio v-model="categoryForm.data.flag" label="2">列表</el-radio>
				</template>
			</el-form-item>
			<el-form-item label="单页模版" v-if="(!categoryForm.data.outside) && (categoryForm.data.flag == 1)" prop="data.page_tpl" style="width: 600px;">
				<template>
					<el-select v-model="categoryForm.data.page_tpl" filterable placeholder="请选择" style="width: 275px;">
						<el-option v-for="(item, index) in pageTpl" :key="item.index" :label="item.name" :value="item.name"></el-option>
					</el-select>
				</template>
			</el-form-item>
			<el-form-item label="列表模版" v-if="(!categoryForm.data.outside) && (categoryForm.data.flag == 2)" prop="data.list_tpl" style="width: 600px;">
				<template>
					<el-select v-model="categoryForm.data.list_tpl" filterable placeholder="请选择" style="width: 275px;">
						<el-option v-for="(item, index) in listTpl" :key="item.index" :label="item.name" :value="item.name"></el-option>
					</el-select>
				</template>
			</el-form-item>
			<el-form-item label="详情模版" v-if="(!categoryForm.data.outside) && (categoryForm.data.flag == 2)" prop="data.detail_tpl" style="width: 600px;">
				<template>
					<el-select v-model="categoryForm.data.detail_tpl" filterable placeholder="请选择" style="width: 275px;">
						<el-option v-for="(item, index) in detailTpl" :key="item.index" :label="item.name" :value="item.name"></el-option>
					</el-select>
				</template>
			</el-form-item>
			<el-form-item label="是否显示" prop="data.display">
				<el-switch v-model="categoryForm.data.display"></el-switch>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" @click="submitForm('categoryForm')" :disabled='categoryForm.submitLock'>
					确 定 <span class="el-icon-loading" v-if='categoryForm.submitLock'></span>
				</el-button>
				<el-button @click="resetForm('categoryForm')" v-if='categoryForm.data.catid==0'>重 置</el-button>
			</el-form-item>
		</el-form>
	</div>
</template>

<script>
import ListTitle from "pc/common/Title"
import UploadOss from "pc/common/UploadOss"
import {changeToBool, changeUploadFormatBack} from "static/js/common.js"
import CurrApp from "pc/common/CurrApp"

export default {
	inject: ['reload'],
	data() {
		return {
			/*appid*/
			appid: this.$route.query.appid,
			currlang: '',//当前选择的语言
			/*头部数据*/
			header: {
				title: '添加栏目',
				reload: false,
				buttons: [
					{
						title: '栏目列表',
						type: 'primary',
						pathName: 'pc/cms/instance/category/CategoryList',
						query: {
							appid: this.$route.query.appid,
						},
					}
				]
			},
			newTags: '',
			tagsLib: [
				// {
				// 	tid: '1',
				// 	tag_name: 'HTML',
				// 	heat: 0
				// },
				// {
				// 	tid: '2',
				// 	tag_name: 'CSS',
				// 	heat: 0
				// }, 
				// {
				// 	tid: '3',
				// 	tag_name: 'YII',
				// 	heat: 0
				// }
			],
			tagsLibLock: false,//获取标签库的锁
			categoryList: [],//所属栏目
			categoryForm: {
				submitLock: false,
				data: {
					catid: 0,
					app_id: 0,
					name: '',
					alias: '',
					icon: [],
					parentid: '',
					preview: [],
					seo_title: '',
					seo_keyword: '',
					seo_describe: '',
					outside: false,
					url_target: '2',
					outside_url: '',
					flag: '2',
					page_tpl: '',
					list_tpl: '',
					detail_tpl: '',
					display: true,
				},
				tags: []
			},
			rules: {
				data: {
					name: [
						{ required: true, message: '请输入栏目名称', trigger: 'blur' },
						{ min: 1, max: 16, message: '长度在 1 到 16 个字符', trigger: 'blur' }
					],
					alias: [
						{ required: true, message: '请输入别名', trigger: 'blur' },
						{ min: 2, max: 32, message: '长度在 2 到 32 个字符', trigger: 'blur' }
					],
					parentid: [
						{ required: true, message: '请选择上级栏目', trigger: 'change' }
					]
				},
			},
			pageTpl: [
				// {'name': 'page-about1'},
				// {'name': 'page-about2'},
				// {'name': 'page-about3'}			
			],
			listTpl: [
				// {'name': 'list-new1'},
				// {'name': 'list-new2'},
				// {'name': 'list-new3'}
			],
			detailTpl: [
				// {'name': 'detail-cjk1'},
				// {'name': 'detail-cjk2'},
				// {'name': 'detail-cjk3'}
			],
		};
	},
	components: {
		ListTitle,
		UploadOss,
		CurrApp
	},
	created: function() {
		/*获取当前语言*/
		let lang = this.$localstorage.get('lang');
		this.currlang = lang?lang:'zh'

		/*取出分类列表 1秒取数据，是防止语言参数没设置上*/
		setTimeout(()=>{
			this.getContentCategoryList()
		}, 500)
		/*取出模版列表*/
		this.getTplList()
		/*如果是修改，取出旧数据*/
		if(this.$route.query.catid){
			this.getCategory(this.$route.query.catid)
		}
	},
	methods: {
		/*获取栏目*/
		getContentCategoryList: function(){
			this.$baseURL(this.$domain.cms)
			this.$get(this.$api.contentCategoryList, {
				appid: this.appid,
				lang: this.currlang
			}).then(res => {
				// console.log(res);
				// if(res.data.code == 10007){//后台提示需要登录
				// 	this.$cookie.remove('isLogin');//刪除cookie登录信息
				// 	this.reload();
				// }
				if(res.data.code === 0){
					if(res.data.data != undefined){
						this.categoryList = []
						Object.keys(res.data.data).forEach((k) => {
							let indent = '';
							for(var i=1; i<res.data.data[k].level; i++){
								if(i == 1){
									indent += '|---';
								}else{
									indent += '---';
								}
							}
							this.categoryList.push ({
								catid: res.data.data[k].catid,
								name: indent + res.data.data[k].name
							});
						})
					}
					this.tableLoading = false
				}
			})
			.catch(err => {})
			.finally(() => {}) 
		},
		/*获取模版列表*/
		getTplList(){
			this.$baseURL(this.$domain.cms)
			this.$get(this.$api.cmsTplList, {
				appid: this.appid,
			}).then(res => {
				// console.log(res);
				// if(res.data.code == 10007){//后台提示需要登录
				// 	this.$cookie.remove('isLogin');//刪除cookie登录信息
				// 	this.reload();
				// }
				if(res.data.code === 0){
					if(res.data.data != undefined){
						// console.log(res.data.data)
						this.categoryList = []
						Object.keys(res.data.data).forEach((k) => {
							if(res.data.data[k].fileName.split('_')[0] == 'page'){
								this.pageTpl.push(
									{'name': res.data.data[k].fileName}
								)
							}
							if(res.data.data[k].fileName.split('_')[0] == 'list'){
								this.listTpl.push(
									{'name': res.data.data[k].fileName}
								)
							}
							if(res.data.data[k].fileName.split('_')[0] == 'detail'){
								this.detailTpl.push(
									{'name': res.data.data[k].fileName}
								)
							}
						})
					}
					this.tableLoading = false
				}
			})
			.catch(err => {})
			.finally(() => {}) 
		},
		/*取出需要修改的数据*/
		getCategory: function(){
			this.header.title = '编辑栏目'
			/*取出需要修改的数据*/
			this.categoryForm.submitLock = true;
			this.$baseURL(this.$domain.cms)
			this.$get(this.$api.modifyContentCategory, {
				appid: this.appid,
				'catid': this.$route.query.catid
			}).then(res => {
				// if(res.data.code == 10007){//后台提示需要登录
				// 	this.$cookie.remove('isLogin');//刪除cookie登录信息
				// 	this.reload();
				// }
				if(res.data.code == 0){
					// console.log(res.data.data)
					this.categoryForm.data.catid = res.data.data.category.catid
					this.categoryForm.data.app_id = res.data.data.category.app_id
					this.categoryForm.data.name = res.data.data.category.name
					this.categoryForm.data.alias = res.data.data.category.alias
					this.categoryForm.data.icon = changeUploadFormatBack(res.data.data.category.icon)
					this.categoryForm.data.parentid = res.data.data.category.parentid
					this.categoryForm.data.preview = changeUploadFormatBack(res.data.data.category.preview)
					this.categoryForm.data.seo_title = res.data.data.category.seo_title
					this.categoryForm.data.seo_keyword = res.data.data.category.seo_keyword
					this.categoryForm.data.seo_describe = res.data.data.category.seo_describe
					this.categoryForm.data.outside = changeToBool(res.data.data.category.outside)
					this.categoryForm.data.url_target = res.data.data.category.url_target
					this.categoryForm.data.outside_url = res.data.data.category.outside_url
					this.categoryForm.data.flag = res.data.data.category.flag
					this.categoryForm.data.page_tpl = res.data.data.category.page_tpl
					this.categoryForm.data.list_tpl = res.data.data.category.list_tpl
					this.categoryForm.data.detail_tpl = res.data.data.category.detail_tpl
					this.categoryForm.data.display = changeToBool(res.data.data.category.display)

					Object.keys(res.data.data.tags).forEach((k) => {
						// console.log(res.data.data.tags[k].tag.tag_name, '111');
						this.categoryForm.tags.push (
							{
								tid: res.data.data.tags[k].tag.tid,
								tag_name: res.data.data.tags[k].tag.tag_name,
								heat: res.data.data.tags[k].tag.heat
							}
						)
					})
				}else{
					this.$message({
						showClose: true,
						message: res.data.info,
						type: 'error'
					});
				}
				this.categoryForm.submitLock = false;
			})
			.catch(err => {})
			.finally(() => {}) 
		},
		/*提交添加、修改表单*/
		submitForm(formName) {
			if(!this.categoryForm.submitLock){
				this.$refs[formName].validate((valid) => {
					if (valid) {
						// console.log(this.categoryForm.tags)
						// return
						this.categoryForm.submitLock = true;
						/*添加、修改分类*/
						let apiUrl = this.$api.addContentCategory//默认是添加
						if(this.categoryForm.data.catid > 0){//修改
							apiUrl = this.$api.modifyContentCategory
						}

						this.categoryForm.data.lang = this.currlang
						let data = JSON.parse(JSON.stringify(this.categoryForm.data))
						// for(let i=0; i<data.preview.length; i++){
						// 	data.preview[i].url = '/' + data.preview[i].url
						// }

						/*添加菜单*/
						this.$baseURL(this.$domain.cms)
						this.$post(apiUrl, {
							appid: this.appid,
							ContentCategory: data,
							Tags: this.categoryForm.tags,
						}).then(res => {
							// console.log(res);
							/*成功*/
							if(res.data.code == 0){
								this.$message({
									showClose: true,
									message: res.data.info,
									type: 'success'
								});
								if(this.categoryForm.data.catid > 0){
									this.$router.go(-1)	
								}else{
									this.$refs[formName].resetFields();
									this.getContentCategoryList();
									this.categoryForm.tags = []
								}
							}else{
								this.$message({
									showClose: true,
									message: res.data.info,
									type: 'error'
								});
							}
							this.categoryForm.submitLock = false;
						});
					} else {
						console.log('error submit!!');
						return false;
					}
				});
			}
		},
		/*重置表单*/
		resetForm(formName) {
			this.$refs[formName].resetFields();
		},
		/*产生新标签*/
		createTag() {
			if(this.newTags != ''){
				let tmp = this.newTags.split(',')
				tmp.forEach((item, index)=>{
					let newTag = {
									tid: '',
									tag_name: item,
									heat: 0
								}
					if(!this.__hasTag(newTag)){
						this.categoryForm.tags.push(newTag)
					}
				})
				this.newTags = ''
			}
		},
		/*删除标签*/
		removeTag(index) {
			this.categoryForm.tags.splice(index, 1);
		},
		/*加载热度高的标签*/
		getHotTags() {
			this.tagsLibLock = true
			this.$get(this.$api.cmsTagsList, {
				appid: this.appid,
				hot: 50
			}).then(res => {
				if(res.data.code == 10007){//后台提示需要登录
					this.$cookie.remove('isLogin');//刪除cookie登录信息
					this.reload();
				}
				if(res.data.code == 0){
					// console.log(res.data.data.list)
					this.tagsLib = []
					Object.keys(res.data.data.list).forEach((k) => {
						this.tagsLib.push(
							{
								tid: res.data.data.list[k].tid,
								tag_name: res.data.data.list[k].tag_name,
								heat: res.data.data.list[k].heat,
							}
						)
					})
					this.tagsLibLock = false
				}else{
					this.$message({
						showClose: true,
						message: res.data.info,
						type: 'error'
					});
				}
				this.categoryForm.submitLock = false;
			})
			.catch(err => {})
			.finally(() => {}) 
		},
		/*库中选择并添加标签*/
		addTag(tag) {
			if(!this.__hasTag(tag)){
				this.categoryForm.tags.push(tag)
			}
		},
		/*判断 已添加的标签中，是否包含此标签*/
		__hasTag(tag) {
			let has = false
			this.categoryForm.tags.forEach((item, index)=>{
				if((item.tid == tag.tid && item.tid != '') || item.tag_name == tag.tag_name){
					has = true
				}
			})
			return has
		},
		/*插入上传的图片*/
		// insertPic(list, field){
		// 	for(let i=0; i<list.length; i++){
		// 		this.categoryForm.data[field].push(
		// 			{
		// 				name: '',
		// 				url:  list[i].url
		// 			}
		// 		)
		// 	}
		// },
		/*删除上传的图片*/
		// delPic(index, field){
		// 	this.categoryForm.data[field].splice(index, 1)
		// },
		/*插入上传的文件*/
		insertIcon(file){
			// console.log(file instanceof Array)
			if(file instanceof Array){//如果是数组的话，说明是图片
				for(let i=0; i<file.length; i++){
					this.categoryForm.data.icon.push(
						{
							name: '',
							url:  file[i].url
						}
					)
				}
			}else{//单个文件路径

			}
		},
		/*删除上传的文件*/
		delIcon(index){
			if(index >= 0){//图片
				this.categoryForm.data.icon.splice(index, 1)
			}else{//文件路径

			}
		},
		/*插入上传的文件*/
		insertPreview(file){
			// console.log(file instanceof Array)
			if(file instanceof Array){//如果是数组的话，说明是图片
				for(let i=0; i<file.length; i++){
					this.categoryForm.data.preview.push(
						{
							name: '',
							url:  file[i].url
						}
					)
				}
			}else{//单个文件路径

			}
		},
		/*删除上传的文件*/
		delPreview(index){
			if(index >= 0){//图片
				this.categoryForm.data.preview.splice(index, 1)
			}else{//文件路径

			}
		},
	},
    computed: {

    }
};
</script>

<style lang="stylus" scoped>
.category
	form
		margin-top: 10px
		.tag
			// border: red 1px solid
			padding-top: 10px
			width: 453px
			overflow: hidden
			li
				float: left
				border: #d6d6d6 1px solid
				margin-right: 10px
				margin-bottom: 10px
				cursor: pointer
				position: relative
				span
					display: block
					padding: 0 10px
					height: 100%
					font-size: 12px
		 	li:hover i
				display: block
			li
				i
					width: 18px
					height: 18px
					line-height: 18px
					font-style: normal
					text-align: center
					color: #fff
					position: absolute
					display: inline-block
					border-radius: 100%
					background-color: rgba(0, 0, 0, .5)
					top: -9px
					right: -9px
					display: none
			li
				i:hover
					background-color: rgba(0, 0, 0, 1)
		.tag-lib
			border: #4abadb 1px solid
			padding: 0 10px
			overflow: hidden
			li
				float: left
				cursor: pointer
				padding: 0px
				// border: red 1px solid
				margin-right: 10px
				span
					font-size: 12px
			li:hover
				color: #4abadb
</style>